<template>
  <el-form
    ref="deptForm"
    label-width="120px"
    :model="form"
    :rules="rules"
  >
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option
          v-for="item in list"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployeeSimple } from '@/api/employees'
import { addDepartments, getDepartmentsById, updateDepartments } from '@/api/departments'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    // 接收isedit的状态
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 1. 自定义校验 不能输入相同的code
    const validCode = (rule, value, callback) => {
      // console.log('value', value)
      const existCodeList = this.originList.map(item => item.code)
      // 判定是否包含相同的code
      if (existCodeList.includes(value)) {
        callback(new Error(`有相同的${value}`))
        // 判断编辑状态时,需要把当前部门的编码在已经存在的数组中移除
        if (this.isEdit) {
          const existCodeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
          console.log('过滤的id', this.originList.filter(item => item.id !== this.id))
          console.log(existCodeList)
        }
      } else {
        callback() // 没有相同的放行
      }
    }
    // 2. 自定义校验,不能输入同级的部门
    const validName = (rule, value, callback) => {
      // 找到当前点击的部门的id
      const existNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      console.log(this.originList.filter(item => item.pid === this.id))
      if (this.isEdit) {
        // 找到兄弟部门
        const pid = this.originList.find(item => item.id === this.id).pid // 获取到当前编辑的部门的id，获取到当前编辑部门的pid
        // console.log('pid', pid)
        const brother = this.originList.filter(item => item.pid === pid) // 通过pid去所有的部门数据中找当前编辑部门的所有的兄弟
        // console.log('brother', brother)
        brother.filter(item => item.id !== this.id).map(item => item.name)
      // console.log(brother.filter(item => item.id !== this.id))
      }
      // 判断是否有相同的名字
      if (existNameList.includes(value)) {
        callback(new Error(`有相同的${value}`))
      } else {
        callback()
      }
    }
    return {
      list: [], // 放员工简单列表
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门负责人
        introduce: '' // 部门介绍
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 10, message: '部门名称要求1-10个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 10, message: '部门编码要求1-10个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadEmployeeSimple()
    // isEdit为true的时候为编辑的时候猜需要获取数据,false则是新增不需要
    if (this.isEdit) {
      this.loadDepartmentsById()
    }
  },
  methods: {
    // 重置表单
    resetForm() {
      this.$refs.deptForm.resetFields()
    },
    // 获取部门详情数据
    async loadDepartmentsById() {
      try {
        const res = await getDepartmentsById(this.id)
        console.log('部门详情数据', res)
        if (res.code === 10000) {
          this.form = res.data // 把获取到的用户详情绑定在表单上显示
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 获取用户的简单信息
    async loadEmployeeSimple() {
      try {
        const res = await getEmployeeSimple()
        console.log('员工简单信息', res)
        this.list = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 新增部门
    async doAdd() {
      try {
        const res = await addDepartments({ pid: this.id, ...this.form })
        console.log('新增部门', res)
        // 错误提示
        if (res.code !== 10000) return this.$message.error(res.message) // 失败
        this.$message.success(res.message) // 成功
        // 子传父 /重新渲染 关闭弹窗
        // 子组件触发事件
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑功能
    async doEdit() {
    //  发送请求
      try {
        const res = await updateDepartments(this.form)
        console.log('修改部门', res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 重新渲染 关闭弹层
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    hSubmit() {
      // 兜底校验
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return // 校验失败
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    hCancel() {
    // b1. 子传父 点击取消父组件的dialog关闭
      this.$emit('close')
    }
  }

}
</script>

<style>

</style>
